<template>
	<view>
		<view style="font-size:28rpx;line-height:20px;color: #999;padding:20px;">
			提示：每日23:30查出看视频大于等于30次的用户列表。可选择对某个用户发放奖励，每个用户仅可发放一次奖励。</view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="warn" size="mini" @click="batchRewardFen">批量发放奖励</button>
			</view>
		</view>
		<view class="uni-container">
			<uni-table border stripe type="selection" ref="uniTable" @selection-change="selectionChange">
				<uni-tr>
					<uni-th align="center">收益人ID</uni-th>
					<uni-th align="center">看视频次数</uni-th>
					<uni-th align="center">奖励金额</uni-th>
					<uni-th width="170" align="center">时间</uni-th>
					<uni-th width="170" align="center">操作</uni-th>
				</uni-tr>
				<uni-tr v-for="(item,index) in data" :key="index" :selectable="item.reward_fen == 0">
					<uni-td align="center">{{item.user_id}}</uni-td>
					<uni-td align="center">{{item.times}}</uni-td>
					<uni-td align="center">{{item.reward_fen/1000}}</uni-td>
					<uni-td align="center">
						<uni-dateformat :date="item.create_date" :threshold="[0, 0]" />
					</uni-td>
					<uni-td align="center">
						<view class="uni-group">
							<button v-if="item.reward_fen" class="uni-button" size="mini" type="default">已发放</button>
							<button v-else @click="update(item,index)" class="uni-button" size="mini"
								type="primary">发放奖励</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
			<view class="uni-pagination-box">
				<uni-pagination show-icon :page-size="pageSize" v-model="pageCurrent" :total="paginationCount"
					@change="onPageChanged" />
			</view>
		</view>
		<uni-popup ref="changePopup" type="center">
			<view class="modal" style="width:450px; padding: 20px;background-color: #FFFFFF;">
				<view class="uni-container">
					<uni-forms ref="form" validateTrigger="bind">
						<uni-forms-item label="奖励金额(元)" name="title" labelWidth="100">
							<input class="uni-input-border" type="text" placeholder="请输入奖励金额"
								v-model="changeRewardFen" />
						</uni-forms-item>
						<view class="uni-button-group pointer"><button class="uni-button uni-button-full" type="primary"
								:disabled="isLoading" @click="save">保存</button></view>
					</uni-forms>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="changeBatchPopup" type="center">
			<view class="modal" style="width:450px; padding: 20px;background-color: #FFFFFF;">
				<view class="uni-container">
					<uni-forms ref="form" validateTrigger="bind">
						<uni-forms-item label="奖励金额(元)" name="title" labelWidth="100">
							<input class="uni-input-border" type="text" placeholder="请输入奖励金额"
								v-model="changeBatchRewardFen" />
						</uni-forms-item>
						<view class="uni-button-group pointer"><button class="uni-button uni-button-full" type="primary"
								:disabled="isLoading" @click="saveBatch">保存</button></view>
					</uni-forms>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const db = uniCloud.database()
	// 表查询配置
	const dbSearchFields = ['uid'] // 支持模糊搜索的字段列表
	// 分页配置
	// const pageSize = 2
	// const pageCurrent = 1

	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				data: [],
				active_index: false,
				changeRewardFen: '',
				isLoading: false,
				query: '',
				where: '',
				pageSize:20,
				pageCurrent: 1,
				paginationCount: "",
				selectedIndexs: [],
				changeBatchRewardFen: '',
				batchIndex: '',
				batchUserId: '',
				checkBarchList:[]
				// options: {
				// 	pageSize,
				// 	pageCurrent
				// }
			}
		},
		computed: {
			...mapState('user', ['userInfo']),
		},
		onLoad() {
			this.getData()
			this.getCount()
		},
		methods: {
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			batchRewardFen() {
				this.checkBarchList = this.data.filter((item,index)=>{
					return this.selectedIndexs.includes(index)
				})
				if(this.selectedIndexs.length == 0){
					uni.showToast({
						title: '至少选择一个才可进行批量操作',
						icon:'none',
						duration:3000
					});
					return false
				}
				this.$refs.changeBatchPopup.open()
			},
			async saveBatch() {
				this.isLoading = true
				let batchRewardFen = (this.changeBatchRewardFen * 1000) / 1;
				// console.log("batchRewardFen: ", batchRewardFen);
				
				for (var i = 0; i < this.checkBarchList.length; i++) {
					let barchRes = await db.action('addReward')
						.collection("video-reward")
						.where({
							_id:this.checkBarchList[i]._id,
							user_id:this.checkBarchList[i].user_id,
							reward_fen:0
						})
						.update({reward_fen:batchRewardFen});
					
					// console.log("barchRes: ",barchRes);
					this.checkBarchList[i].reward_fen = batchRewardFen
				}
				this.isLoading = false
				this.$refs.changeBatchPopup.close()
			},
			async getCount() {
				const {
					result: totalCount
				} = await db.collection('video-reward').count()
				this.paginationCount = totalCount.total
			},
			async getData() {
				const {
					result: videoRewardList
				} = await db.collection('video-reward').orderBy("create_date", "desc")
					.skip(this.pageSize * (this.pageCurrent - 1)).limit(this.pageSize).get()

				// console.log("videoRewardList: ", videoRewardList);
				this.data = videoRewardList.data
			},
			async save() {
				this.isLoading = true
				let item = this.data[this.active_index];
				let reward_fen = (this.changeRewardFen * 1000) / 1;
				let res = await db.action('addReward')
					.collection("video-reward")
					.where({
						_id:item._id,
						user_id: item.user_id,
						reward_fen: 0
					})
					.update({
						reward_fen
					});
				this.isLoading = false
				item.reward_fen = reward_fen
				this.$refs.changePopup.close()
			},
			update(item, index) {
				this.active_index = index
				this.$refs.changePopup.open()
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				const isSameWhere = newWhere === this.where
				this.where = newWhere
				if (isSameWhere) { // 相同条件时，手动强制刷新
					// this.loadData()
				}
			},
			onPageChanged(e) {
				this.pageCurrent = e.current
				this.getData()
			}
		}
	}
</script>
<style>
</style>
